package com.ymy.spring.cloud.sentinel.core.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.ymy.spring.cloud.sentinel.core.config.SentinelConfig.RESOURCE_NAME;

/**
 * sentinel 流控规则测试
 *
 * @author Ringo
 * @date 2021/10/5 17:02
 */
@RestController
public class FlowRulesController {


    @GetMapping("/hello")
    public String hello() {
        Entry entry = null;
        try {
            // sentinel 针对目标资源进行流量控制
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            String s = "hello world";
            System.out.println(s);
            return s;
        } catch (BlockException e) {
            // 资源访问阻止, 被限流或者被降级
            System.out.println("BlockException");
            return "被流控了";
        } catch (Throwable t) {
            // 业务异常
            System.out.println("业务异常");
            return "业务异常";
        } finally {
            if (entry != null) {
                entry.close();
            }
        }
    }

}
